using DapperExtensionsNew.Configuration;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

namespace DapperExtensionsNew.Queryable.Analyzers
{
	public class StringContains : Where
	{
		protected static readonly string Suffix = "Pattern";

		protected override bool IsSatisfied(Context context, PropertyInfo queryProperty)
		{
			if (!(queryProperty.PropertyType == typeof(string)))
			{
				return false;
			}
			if (!queryProperty.Name.EndsWith(Suffix))
			{
				return false;
			}
			string targetModelPropertyName = queryProperty.Name.Substring(0, queryProperty.Name.Length - Suffix.Length);
			PropertyInfo propertyInfo = context.ModelProperties.FirstOrDefault((PropertyInfo x) => x.Name == targetModelPropertyName);
			if (!(propertyInfo == null))
			{
				return propertyInfo.PropertyType == queryProperty.PropertyType;
			}
			return false;
		}

		protected override Expression GetWhereClause(Context context, PropertyInfo queryProperty)
		{
			string text = queryProperty.Name.Substring(0, queryProperty.Name.Length - Suffix.Length);
			MemberExpression memberExpression = Expression.Property(context.QueryExpression, queryProperty);
			SqlDatabaseOptions sqlDatabaseOptions = SqlDatabaseOptionsFactory.GetSqlDatabaseOptions(context.Analyzer);
			string startDelimiter = sqlDatabaseOptions.StartDelimiter;
			string endDelimiter = sqlDatabaseOptions.EndDelimiter;
			Expression expression = Expression.Constant("@" + queryProperty.Name);
			Expression stringParam = ConcatExpression(Expression.Constant(" AND " + startDelimiter + text + endDelimiter + " like "), expression);
			Expression valueExpr = ConcatExpression(Expression.Constant("%"), memberExpression, Expression.Constant("%"));
			BlockExpression ifTrue = Expression.Block(CallStringBuilderAppend(context.SqlExpression, stringParam), CallAddParameters(context.ParametersExpression, expression, valueExpr));
			return Expression.IfThen(Expression.NotEqual(memberExpression, Expression.Constant(null)), ifTrue);
		}
	}
}
